<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="路段名称" prop="roadName">
        <el-select v-model="queryParams.roadName" placeholder="请选择路段名称" clearable filterable>
          <el-option
            v-for="dict in dict.type.sys_road"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
	    <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['functiontest:EtcGantryTreeTest:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['functiontest:EtcGantryTreeTest:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['functiontest:EtcGantryTreeTest:import']"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-check"
          size="mini"
          @click="handleFieldAudit"
          v-hasPermi="['functiontest:EtcGantryTreeTest:fieldAudit']"
        >实测单位审核</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-check"
          size="mini"
          @click="handleOwnerAudit"
          v-hasPermi="['functiontest:EtcGantryTreeTest:ownerAudit']"
        >业主审核</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-check"
          size="mini"
          @click="handleCenterAudit"
          v-hasPermi="['functiontest:EtcGantryTreeTest:centerAudit']"
        >中心审核</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-sort"
          size="mini"
          @click="toggleExpandAll"
        >展开/折叠</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="EtcGantryTreeTestList"
      row-key="id"
      :default-expand-all="isExpandAll"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column label="父节点ID" prop="parentId" />
      <el-table-column label="路段名称" align="center" prop="roadName">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_road" :value="scope.row.roadName"/>
        </template>
      </el-table-column>
      <el-table-column label="ETC门架序号" align="center" prop="etcCode" />
      <el-table-column label="ETC门架区间" align="center" prop="nodeName" />
      <el-table-column label="经度" align="center" prop="longitude" />
      <el-table-column label="纬度" align="center" prop="latitude" />
      <el-table-column label="门架位置" align="center" prop="gantryLocation">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_gantry_position" :value="scope.row.gantryLocation"/>
        </template>
      </el-table-column>
      <el-table-column label="备注信息" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['functiontest:EtcGantryTreeTest:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            v-hasPermi="['functiontest:EtcGantryTreeTest:add']"
            v-if="getNodeLevel(scope.row) < 3"
          >新增</el-button>

          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['functiontest:EtcGantryTreeTest:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改ETC门架区间数据测试对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!-- 父节点ID字段（隐藏显示，但保留用于数据提交） -->
        <el-form-item label="父节点ID" prop="parentId" style="display: none;">
          <treeselect v-model="form.parentId" :options="EtcGantryTreeTestOptions" :normalizer="normalizer" placeholder="请选择父节点ID" />
        </el-form-item>
        
        <!-- 第一层新增对话框只显示路段名称 -->
        <el-form-item label="路段名称" prop="roadName" v-if="addLevel === 1">
          <el-select v-model="form.roadName" placeholder="请选择路段名称" clearable filterable>
            <el-option
              v-for="dict in dict.type.sys_road"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        
        <!-- 第一层到第二层的新增对话框只显示ETC门架序号、ETC门架区间、备注信息 -->
        <template v-if="addLevel === 2">
          <el-form-item label="ETC门架序号" prop="etcCode">
            <el-input v-model="form.etcCode" placeholder="请输入ETC门架序号" />
          </el-form-item>
          <el-form-item label="ETC门架区间" prop="nodeName">
            <el-input v-model="form.nodeName" placeholder="请输入ETC门架区间" />
          </el-form-item>
          <el-form-item label="备注信息" prop="remark">
            <el-input v-model="form.remark" placeholder="请输入备注信息" />
          </el-form-item>
        </template>
        
        <!-- 第二层到第三层的新增对话框只显示经度、纬度、门架位置 -->
        <template v-if="addLevel === 3">
          <el-form-item label="经度" prop="longitude">
            <el-input v-model="form.longitude" placeholder="请输入经度" />
          </el-form-item>
          <el-form-item label="纬度" prop="latitude">
            <el-input v-model="form.latitude" placeholder="请输入纬度" />
          </el-form-item>
          <el-form-item label="门架位置" prop="gantryLocation">
            <el-select v-model="form.gantryLocation" placeholder="请选择门架位置" clearable filterable>
              <el-option
                v-for="dict in dict.type.sys_gantry_position"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listEtcGantryTreeTest, getEtcGantryTreeTest, delEtcGantryTreeTest, addEtcGantryTreeTest, updateEtcGantryTreeTest, exportEtcGantryTreeTest, importEtcGantryTreeTest, importTemplateEtcGantryTreeTest, fieldAuditEtcGantryTreeTestBatch, ownerAuditEtcGantryTreeTestBatch, centerAuditEtcGantryTreeTestBatch } from "@/api/functiontest/EtcGantryTreeTest"
import Treeselect from "@riophae/vue-treeselect"
import "@riophae/vue-treeselect/dist/vue-treeselect.css"
import { getUserProfile } from "@/api/system/user"

export default {
  name: "EtcGantryTreeTest",
  dicts: ['sys_gantry_position', 'sys_road'],
  components: {
    Treeselect
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // ETC门架区间数据测试表格数据
      EtcGantryTreeTestList: [],
      // ETC门架区间数据测试树选项
      EtcGantryTreeTestOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部展开
      isExpandAll: false,
      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {
        roadName: null,
        etcCode: null,
        nodeName: null,
        deptId: null,
        roleId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      deptId: null,
      roleId: null,
      // 新增节点层级标识：1-第一层，2-第二层，3-第三层
      addLevel: 1,
      // 上传参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + this.$store.getters.token },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/functiontest/EtcGantryTreeTest/importData"
      },
    }
  },
  created() {
    this.getUser().then(() => {
      this.getList();
    });
  },
  methods: {
    getUser() {
      return getUserProfile().then(response => {
        if(response.data.roles[0].roleId != 1) {
          this.deptId = response.data.dept.deptId
        }else{
          this.deptId = null
        }
        this.roleId = response.data.roles[0].roleId
      })
    },
    /** 查询ETC门架区间数据测试列表 */
    getList() {
      this.queryParams.deptId = this.deptId
      this.queryParams.roleId = this.roleId
      this.loading = true
      listEtcGantryTreeTest(this.queryParams).then(response => {
        this.EtcGantryTreeTestList = this.handleTree(response.data, "id", "parentId")
        this.loading = false
      })
    },
    /** 转换ETC门架区间数据测试数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.id,
        label: node.roadName,
        children: node.children
      }
    },
	/** 查询ETC门架区间数据测试下拉树结构 */
    getTreeselect() {
      listEtcGantryTreeTest().then(response => {
        this.EtcGantryTreeTestOptions = []
        const data = { id: 0, roadName: '顶级节点', children: [] }
        data.children = this.handleTree(response.data, "id", "parentId")
        this.EtcGantryTreeTestOptions.push(data)
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        parentId: null,
        roadName: null,
        etcCode: null,
        nodeName: null,
        longitude: null,
        latitude: null,
        gantryLocation: null,
        remark: null
      }
      this.addLevel = 1 // 重置新增层级标识
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset()
      this.getTreeselect()
      if (row != null && row.id) {
        this.form.parentId = row.id
        // 判断新增层级：如果父节点parentId为0，则新增第二层；否则新增第三层
        if (row.parentId === 0) {
          this.addLevel = 2 // 新增第二层
        } else {
          this.addLevel = 3 // 新增第三层
        }
      } else {
        this.form.parentId = 0
        this.addLevel = 1 // 新增第一层
      }
      this.open = true
      this.title = "添加ETC门架区间数据测试"
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false
      this.isExpandAll = !this.isExpandAll
      this.$nextTick(() => {
        this.refreshTable = true
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.getTreeselect()
      if (row != null) {
        this.form.parentId = row.parentId
        // 判断修改层级：如果当前节点parentId为0，则修改第一层；如果父节点parentId为0，则修改第二层；否则修改第三层
        if (row.parentId === 0) {
          this.addLevel = 1 // 修改第一层
        } else {
          // 需要查找父节点来判断层级
          const parentNode = this.findParentNode(row.parentId)
          if (parentNode && parentNode.parentId === 0) {
            this.addLevel = 2 // 修改第二层
          } else {
            this.addLevel = 3 // 修改第三层
          }
        }
      }
      getEtcGantryTreeTest(row.id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改ETC门架区间数据测试"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateEtcGantryTreeTest(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addEtcGantryTreeTest(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除ETC门架区间数据测试编号为"' + row.id + '"的数据项？').then(function() {
        return delEtcGantryTreeTest(row.id)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.$modal.confirm('是否确认导出所有ETC门架区间数据测试项？').then(() => {
        return exportEtcGantryTreeTest(this.queryParams)
      }).then(response => {
        this.$download.saveAs(response, 'ETC门架区间数据测试.xlsx')
      }).catch(() => {})
    },
    
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "ETC门架区间数据测试导入"
      this.upload.open = true
    },
    
    /** 下载模板操作 */
    importTemplate() {
      importTemplateEtcGantryTreeTest().then(response => {
        this.$download.saveAs(response, 'ETC门架区间数据测试导入模板.xlsx')
      })
    },
    
    /** 文件上传中处理 */
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    
    /** 文件上传成功处理 */
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true })
      // 导入成功后强制刷新树形结构，确保分层显示
      this.loading = true
      listEtcGantryTreeTest(this.queryParams).then(response => {
        this.EtcGantryTreeTestList = this.handleTree(response.data, "id", "parentId")
        this.loading = false
        // 自动展开所有节点，让用户看到分层效果
        this.$nextTick(() => {
          this.isExpandAll = true
          this.refreshTable = false
          this.$nextTick(() => {
            this.refreshTable = true
          })
        })
      })
    },
    
    /** 提交上传文件 */
    submitFileForm() {
      const file = this.$refs.upload.uploadFiles
      if (!file || file.length === 0 || !file[0].name.toLowerCase().endsWith('.xls') && !file[0].name.toLowerCase().endsWith('.xlsx')) {
        this.$modal.msgError("请选择后缀为 “xls”或“xlsx”的文件。")
        return
      }
      this.$refs.upload.submit()
    },
    
    /** 实测单位审核按钮操作 */
    handleFieldAudit() {
      this.$modal.confirm('是否确认对当前所有ETC门架区间数据测试项进行实测单位审核？').then(() => {
        return fieldAuditEtcGantryTreeTestBatch()
      }).then(response => {
        this.$modal.msgSuccess("实测单位批量审核成功")
        this.getList()
      }).catch(() => {})
    },
    
    /** 业主审核按钮操作 */
    handleOwnerAudit() {
      this.$modal.confirm('是否确认对当前所有ETC门架区间数据测试项进行业主审核？').then(() => {
        return ownerAuditEtcGantryTreeTestBatch({
          deptId: this.deptId,
          roleId: this.roleId
        })
      }).then(response => {
        this.$modal.msgSuccess("业主批量审核成功")
        this.getList()
      }).catch(() => {})
    },
    
    /** 中心审核按钮操作 */
    handleCenterAudit() {
      this.$modal.confirm('是否确认对当前所有ETC门架区间数据测试项进行中心审核？').then(() => {
        return centerAuditEtcGantryTreeTestBatch()
      }).then(response => {
        this.$modal.msgSuccess("中心批量审核成功")
        this.getList()
      }).catch(() => {})
    },
    
    /** 查找指定ID的节点 */
    findNodeById(id, nodes) {
      if (!nodes) {
        nodes = this.EtcGantryTreeTestList
      }
      
      for (let node of nodes) {
        if (node.id === id) {
          return node
        }
        if (node.children && node.children.length > 0) {
          const found = this.findNodeById(id, node.children)
          if (found) {
            return found
          }
        }
      }
      return null
    },
    
    /** 查找指定ID节点的父节点 */
    findParentNode(id) {
      return this.findNodeById(id, this.EtcGantryTreeTestList)
    },
    
    /** 获取节点层级 */
    getNodeLevel(row) {
      // 判断节点层级：如果parentId为0，则为第一层；如果父节点parentId为0，则为第二层；否则为第三层
      if (row.parentId === 0) {
        return 1 // 第一层
      } else {
        // 查找父节点来判断层级
        const parentNode = this.findParentNode(row.parentId)
        if (parentNode && parentNode.parentId === 0) {
          return 2 // 第二层
        } else {
          return 3 // 第三层
        }
      }
    }
  }
}
</script>
